package com.zprmb.udzt;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.zprmb.udzt.gesture.GestureVerifyActivity;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.MySharePreferenceUtil;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.util.VolleryUtil3;
import com.zprmb.udzt.view.WebViewDialog;

import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
//import android.webkit.JavascriptInterface;
//import android.webkit.SslErrorHandler;
//import android.webkit.WebChromeClient;
//import android.webkit.WebResourceResponse;
//import android.webkit.WebSettings;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;


@SuppressLint("SetJavaScriptEnabled")
public class V6WebviewActivity extends BaseActivity3 implements PullToRefreshBase.OnRefreshListener<ScrollView> {

    private ImageView iv_v4_web_back;
    private TextView tv_v4_web_title;
    private String title;
    private String ref = "";
    private String url;
    private View web_head_view;
    private WebView v4_webview;
    private RelativeLayout rl_back;
    //	private ProgressBar bar;
    private boolean back = false;
    private SharedPreferences sha;
    private ImageView iv_v4_nonetwork;
    private WebViewDialog dialog;
    private int active;
    private String active_url;
    int flag;
    Map<String, String> extraHeaders;
    private boolean loadError = false;
    private int reload = 0;
    //下拉刷新
    PullToRefreshScrollView sv;
    String token;
    private final String ACTION_NAME = "个人中心结束";
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_NAME)) {
                finish();
            }
        }

    };

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    private final String ACTION_NAME2 = "跳转到登录";
    private BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_NAME2)) {
//                Toast.makeText(V6DetailsActivity.this, "处理action名字相对应的广播", 200);
                Intent intent2 = new Intent(V6WebviewActivity.this,
                        V6LoginActivity.class);
                intent2.putExtra("close", 1);

                startActivityForResult(intent2, 1);

//                finish();
            }
        }

    };

    public void registerBoradcastReceiver2() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME2);
        //注册广播
        registerReceiver(mBroadcastReceiver2, myIntentFilter);
    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v4_webview_activity);
        BbtApplication.getInstance().addActvity(this);
        setImmersionStatus();
//        EventBus.getDefault().register(this);
        registerBoradcastReceiver();
        registerBoradcastReceiver2();
        Intent intent = getIntent();
        verifuser("1");
        token = (String) MySharePreferenceUtil.get(this, "mytoken", "");

        try {
            token = URLEncoder.encode(token, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
        active = intent.getIntExtra("active", 0);
        active_url = intent.getStringExtra("active_url");
        ref = getShare().getString("usercode", "");
//		Log.e("webview", url);
        dialog = new WebViewDialog(this);
        // url = "account/invest/8F759CC2-65DB-11E5-AE96-5254002EAABD/contract";
        sha = getSharedPreferences("config", MODE_PRIVATE);
        initView();
        initData();
        flag = getIntent().getIntExtra("flag", 0);


        token = (String) MySharePreferenceUtil.get(V6WebviewActivity.this, "mytoken", "");

        try {
            token = URLEncoder.encode(token, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (active == 1) {
//            v4_webview.loadUrl(active_url + "&app=true&appversion=true&token=" + getURLToken(), extraHeaders);
            v4_webview.loadUrl(active_url + "&app=true&appversion=true&token=" + token, extraHeaders);
            active = 0;
        } else {
//            v4_webview.loadUrl(url + "?app=true&appversion=true&token=" + getURLToken(), extraHeaders);
//
            v4_webview.loadUrl(url + "?app=true&appversion=true&token=" +token, extraHeaders);
        }
        sv = (PullToRefreshScrollView) findViewById(R.id.home_sv);
        sv.getLoadingLayoutProxy().setPullLabel("下拉可刷新");
        sv.getLoadingLayoutProxy().setRefreshingLabel("智慧投资 更优一点");
        sv.getLoadingLayoutProxy().setReleaseLabel("松开即刷新");
        sv.setOnRefreshListener(this);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        BbtApplication.getInstance().removeActvity(this);
        dialog.dismiss();
        unregisterReceiver(mBroadcastReceiver);
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        token = (String) MySharePreferenceUtil.get(this, "mytoken", "");

        try {
            token = URLEncoder.encode(token, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        if (!network()) {
            iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

            v4_webview.setVisibility(View.GONE);
        } else if (iv_v4_nonetwork.getVisibility() == View.VISIBLE) {
            v4_webview.reload();
        } else if (v4_webview.getVisibility() == View.GONE) {
            v4_webview.reload();
        } else {


            if (reload == 1) {
                String url = geturl().substring(1, geturl().length());
                Log.e("url", url);
//                v4_webview.loadUrl(Constant.URL + url + "&token=" + getURLToken());
                v4_webview.loadUrl(Constant.URL + url + "&token=" + token);
                v4_webview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        v4_webview.clearHistory();
                    }
                }, 1000);

            } else {
                if (getFirstType() == 1) {
//                    v4_webview.loadUrl(Constant.URL + "h5/userInfo" + getActive_url() + "&app=true&appversion=true&token=" + getURLToken(), extraHeaders);

                    v4_webview.loadUrl(Constant.URL + "h5/userInfo" + getActive_url() + "&app=true&appversion=true&token=" + token, extraHeaders);
                    Log.e("active_test", Constant.URL + "h5/userInfo" + getActive_url() + "&app=true&appversion=true&token=" +token);
                    Editor editor = getShare().edit();

                    editor.putInt("firstType", 0);

                    editor.commit();
                    return;
                }
                v4_webview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        v4_webview.loadUrl("javascript:updateData('" + getToken() + "')");
                    }
                }, 1000);

            }

        }

//		}
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        return false;
    }

    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }
    };

    private void initData() {
        extraHeaders = new HashMap<String, String>();
        extraHeaders.put("token", getToken());
//		extraHeaders.put("sss", getToken());
        v4_webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("myurl", url + "");
                if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
                    if (url.contains("h5/userInfo")) {

                        view.loadUrl(url);
                        return true;
                    }
                    if (url.contains("redirect")) {
              /*    Intent intent = new Intent(V6WebviewActivity.this,
                                V6LoginActivity.class);
                        intent.putExtra("close", 1);
                        intent.putExtra("assets", 1);
                        intent.putExtra("web", 1);
                        startActivityForResult(intent, 2);*/
                    } else {
                        Log.e("跳转url", url + "");
                        Intent intent = new Intent(V6WebviewActivity.this, V6WebviewChild.class);
                        if (url.contains("?")) {

//                            intent.putExtra("url", url + "&app=true&token=");
                            intent.putExtra("url", url + "&app=true&appversion=true&token=");
                        } else {
                            intent.putExtra("url", url + "?app=true&appversion=true&token=");
                        }
                        startActivityForResult(intent, 2);


//						view.loadUrl(url);
                    }


//			            view.loadUrl(url);
                    return true;
                }

                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
                loadError = true;

            }

            //			@Override
//			public void onReceivedSslError(WebView view,
//					SslErrorHandler handler, SslError error) {
//				// TODO Auto-generated method stub
////				super.onReceivedSslError(view, handler, error);
//				handler.proceed();
//			}
            @Override
            public void onReceivedSslError(WebView arg0, SslErrorHandler arg1,
                                           com.tencent.smtt.export.external.interfaces.SslError arg2) {
                // TODO Auto-generated method stub
//				super.onReceivedSslError(arg0, arg1, arg2);
                arg1.proceed();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == false) {
                    dialog.show();
                }
                loadError = false;
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == true) {
                    dialog.dismiss();

                }
                if (!loadError) {//当网页加载成功的时候判断是否加载成功
                    iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                    v4_webview.setVisibility(View.VISIBLE);

                } else { //加载失败的话，初始化页面加载失败的图，然后替换正在加载的视图页面
                    iv_v4_nonetwork.setVisibility(View.VISIBLE);
                    v4_webview.setVisibility(View.GONE);
                }

                super.onPageFinished(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
                LogUtils.e(V6WebviewActivity.this, "资源" + url);
                WebResourceResponse response = null;
                if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
                    response = super.shouldInterceptRequest(view, url);
                    if (url.contains("forapp=1")) {


                        if (url.contains(".css")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("css") + 3);
//			          			Log.e("css", murl);
                                response = new WebResourceResponse("text/css", "UTF-8", getAssets().open("css" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (url.contains(".png")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("png") + 3);
//			             	Log.e("png", murl);
                                response = new WebResourceResponse("image/png", "UTF-8", getAssets().open("image/" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (url.contains(".js")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("js") + 2);
//			                	  Log.e("css", "有");
                                response = new WebResourceResponse("application/x-javascript", "UTF-8", getAssets().open("public_js/" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                return response;

            }
        });
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);
        // 重新设置websettings WebSettings s = wb.getSettings();
        // s.setBuiltInZoomControls(true);
        // s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();

        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");
        if (v4_webview.getX5WebViewExtension() != null) {

            v4_webview.getX5WebViewExtension().setVerticalTrackDrawable(null);
        }

    }

    private void initData2() {
        extraHeaders = new HashMap<String, String>();
        extraHeaders.put("token", getToken());
//		extraHeaders.put("sss", getToken());
        v4_webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("myurl", url + "");
                if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
                    if (url.contains("h5/userInfo")) {

                        view.loadUrl(url);
                        return true;
                    }
                    if (url.contains("redirect")) {

                    } else {
                        Log.e("跳转url", url + "");
                        Intent intent = new Intent(V6WebviewActivity.this, V6WebviewChild.class);
                        if (url.contains("?")) {

                            intent.putExtra("url", url + "&app=true&appversion=true&token=");
                        } else {
                            intent.putExtra("url", url + "?app=true&appversion=true&token=");
                        }
                        startActivityForResult(intent, 2);

                    }

                    return true;
                }

                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
                loadError = true;

            }


            //			}
            @Override
            public void onReceivedSslError(WebView arg0, SslErrorHandler arg1,
                                           com.tencent.smtt.export.external.interfaces.SslError arg2) {
                // TODO Auto-generated method stub
//				super.onReceivedSslError(arg0, arg1, arg2);
                arg1.proceed();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == false) {
                    dialog.dismiss();
                }
                loadError = false;
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == true) {
                    dialog.dismiss();

                }
                if (!loadError) {//当网页加载成功的时候判断是否加载成功
                    iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                    v4_webview.setVisibility(View.VISIBLE);

                } else { //加载失败的话，初始化页面加载失败的图，然后替换正在加载的视图页面
                    iv_v4_nonetwork.setVisibility(View.VISIBLE);
                    v4_webview.setVisibility(View.GONE);
                }

                super.onPageFinished(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
                LogUtils.e(V6WebviewActivity.this, "资源" + url);
                WebResourceResponse response = null;
                if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
                    response = super.shouldInterceptRequest(view, url);
                    if (url.contains("forapp=1")) {


                        if (url.contains(".css")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("css") + 3);
//			          			Log.e("css", murl);
                                response = new WebResourceResponse("text/css", "UTF-8", getAssets().open("css" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (url.contains(".png")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("png") + 3);
//			             	Log.e("png", murl);
                                response = new WebResourceResponse("image/png", "UTF-8", getAssets().open("image/" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (url.contains(".js")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("js") + 2);
//			                	  Log.e("css", "有");
                                response = new WebResourceResponse("application/x-javascript", "UTF-8", getAssets().open("public_js/" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                return response;

            }
        });
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);
        // 重新设置websettings WebSettings s = wb.getSettings();
        // s.setBuiltInZoomControls(true);
        // s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();

        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");
        if (v4_webview.getX5WebViewExtension() != null) {

            v4_webview.getX5WebViewExtension().setVerticalTrackDrawable(null);
        }


    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);
        if (arg2 != null) {

            if (arg1 == 2) {

//                v4_webview.loadUrl(url + "?app=true&appversion=true&token=" + getURLToken());
                v4_webview.loadUrl(url + "?app=true&appversion=true&token=" + token);
            }
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                share(V6WebviewActivity.this, msg.getData().getString("description"), msg.getData().getString("title"), msg.getData().getString("sharelink"), msg.getData().getString("imageurl"));
            }


        }

        ;
    };
    @SuppressLint("HandlerLeak")
    Handler handler2 = new Handler() {
        public void handleMessage(Message msg) {

            verifuser("1");
            initView();
            initData2();
            flag = getIntent().getIntExtra("flag", 0);

            if (active == 1) {
//                v4_webview.loadUrl(active_url + "&app=true&appversion=true&token=" + getURLToken(), extraHeaders);
                v4_webview.loadUrl(active_url + "&app=true&appversion=true&token=" +token, extraHeaders);
                active = 0;
            } else {
//                v4_webview.loadUrl(url + "?app=true&appversion=true&token=" + getURLToken(), extraHeaders);
//				Log.e("myurl", url+"?app=true&token="+getURLToken());
                v4_webview.loadUrl(url + "?app=true&appversion=true&token=" + token, extraHeaders);
            }

            sv.onRefreshComplete();

        }

    };

    @Override
    public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
        // TODO Auto-generated method stub
        handler2.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                handler2.sendEmptyMessage(1);
            }
        }, 1000);
    }

    private class JsInterfaces {
        private Context mContext;

        public JsInterfaces(Context context) {
            this.mContext = context;
        }

        // 在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void pleaseLogin(String name) {


        }

        @JavascriptInterface
        public void showInfoFromJs(String name) {

            initshare();
        }

        @JavascriptInterface
        public String getToken() {

            return getToken();
        }

        @JavascriptInterface
        public void finishActivity() {

            finish();
        }

        @JavascriptInterface
        public void toproduct(String[] list) {

            // Toast.makeText(Active_Webview.this, list.toString(),
            // 2000).show();

            Intent intent = new Intent(V6WebviewActivity.this,
                    V6DetailsActivity.class);
            intent.putExtra("flag", Boolean.parseBoolean(list[0]));
            intent.putExtra("name", list[1]);
            intent.putExtra("type", list[2]);
            intent.putExtra("id", list[3]);
            intent.putExtra("isred", list[4]);

            startActivity(intent);
        }

        @JavascriptInterface
        public void jsshare2(String sharelink, String description, String title, String imageurl) {
//			Toast.makeText(V4WebViewActivity.this, sharelink+sharelink+title, 2000).show();
            if (sharelink.length() > 1) {
                if (ref.equals("")) {


                } else {
                    sharelink = sharelink + "?ref=" + ref;

                }
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("title", title);
                bundle.putString("sharelink", sharelink);
                bundle.putString("description", description);
                bundle.putString("imageurl", imageurl);
                message.setData(bundle);//bundle传值，耗时，效率低
                handler.sendMessage(message);//发送message信息
                message.what = 1;//标志是哪个线程传数据

            }
        }

        @JavascriptInterface
        public void signout() {
//			SharedPreferences sharedPreferences=getSharedPreferences("config", MODE_PRIVATE);
            Editor ed = getShare().edit();
            ed.putString("token", "");
//			ed.putString("mobile", "");
//			ed.putString("usercode", "");
            ed.commit();
//			MainActivity.newInstance().setCurrentTabByTag("tab_tag_shouye");
            Intent intent9 = new Intent(V6WebviewActivity.this, MainActivity.class);
            intent9.putExtra("who", 2);
            startActivity(intent9);
        }


        @JavascriptInterface
        public void jsshare(String sharelink, String description, String title) {
//			Toast.makeText(V6WebviewActivity.this, sharelink+sharelink+title, 2000).show();
            if (sharelink.length() > 1) {
                shareforjs(sharelink, description, title);

            }
        }

        @JavascriptInterface
        public void settab(int i) {

            Editor ed = sha.edit();
            ed.putInt("tab", i);
            ed.commit();
            Intent intent = new Intent(V6WebviewActivity.this,
                    MainActivity.class);
            intent.putExtra("licai", 1);
            startActivity(intent);
        }

        @JavascriptInterface
        public void setTitle(String title) {
            tv_v4_web_title.setText(title);

        }

        @JavascriptInterface
        public void setactivity(String activity) {


            Intent intent;
            try {
                intent = new Intent(V6WebviewActivity.this,
                        Class.forName(activity));
                intent.putExtra("webview", 1);
                startActivity(intent);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        @JavascriptInterface
        public void setactivityIntent(String activity, String key, String value) {


            Intent intent;
            try {
                intent = new Intent(V6WebviewActivity.this,
                        Class.forName(activity));
                intent.putExtra("webview", 1);
                intent.putExtra(key, value);
                startActivity(intent);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        @JavascriptInterface
        public void addmoney() {
//            verifuser("1");
        }

        public void sendInfoToJs(View view) {
            String msg = getToken();
            Log.e("web", "调用");
            // 调用js中的函数：showInfoFromJava(msg)

        }
    }

    private void initshare() {
        VolleryUtil volleryUtil = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                Log.e("invate", jsonObject.toString());
                if (jsonObject.optInt("success") == 1) {
                    JSONObject json = jsonObject.optJSONObject("data");
                    String linkurl = "";
                    if (ref.equals("")) {
                        linkurl = json.optString("linkUrl");

                    } else {
                        linkurl = json.optString("linkUrl") + "?ref=" + ref;

                    }


                    share(V6WebviewActivity.this, json.optString("description"), json.optString("title"), linkurl, "");
                } else {

                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        volleryUtil.setRequestMethod(0);
        volleryUtil.setShow(true);
        volleryUtil.execute(V6WebviewActivity.this, Constant.URL + "/api/shareProductContent/inviteFriend/inviteFriend", "");
    }

    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    public void shareforjs(String sharelink, String description, String title) {
        if (ref.equals("")) {


        } else {
            sharelink = sharelink + "?ref=" + ref;

        }
        share(V6WebviewActivity.this, description, title, sharelink, "");
    }

    private void verifuser(final String who) {
        VolleryUtil3 volleryUtil = new VolleryUtil3() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                if (jsonObject.optInt("success") == 1) {
                    JSONObject json = jsonObject.optJSONObject("data");
                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6WebviewActivity.this,
                                V6LoginActivity.class);
                        intent.putExtra("close", 1);
                        startActivity(intent);
                    }

                } else {
                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6WebviewActivity.this,
                                V6LoginActivity.class);
//                        intent.putExtra("close", 1);
                        startActivity(intent);
//                        V6WebviewActivity.this.finish();
                    }
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        volleryUtil.setRequestMethod(0);
        volleryUtil.setHeaders("token",

                token);
        volleryUtil.setShow(true);
        volleryUtil.execute(this, Constant.URL + "/api/v5/user/userInfo", "");
    }

    private void initView() {
        iv_v4_web_back = (ImageView) findViewById(R.id.img_back);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        web_head_view = (View) findViewById(R.id.web_head_view);
        iv_v4_nonetwork = (ImageView) findViewById(R.id.iv_v4_nonetwork);
        web_head_view.setVisibility(View.VISIBLE);

        rl_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();

                }
            }
        });
        iv_v4_web_back.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();
                }
            }
        });
        tv_v4_web_title = (TextView) findViewById(R.id.tv_title);
        tv_v4_web_title.getPaint().setFakeBoldText(true);
//		if (title.indexOf("了解") == 0) {
////			tv_v4_web_title.setText("项目详情");
//		} else {
//
////			tv_v4_web_title.setText(title);
//		}
        v4_webview = (WebView) findViewById(R.id.v4_webview);
        iv_v4_nonetwork.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                v4_webview.reload();

            }
        });
    }
}
